package com.nyist.threadCase3;

import com.nyist.thread.NyistThreadUtils;
import lombok.extern.slf4j.Slf4j;

import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 * 1.
 *
 * @ClassName sumNum
 * @Description
 * @Author xiaoyang
 * @Date 2023/04/09/17:17
 */
@Slf4j
public class SumNum implements Runnable {
    private final Integer endNumber;

    Lock lock = new ReentrantLock();

    public SumNum(Integer endNumber) {
        this.endNumber = endNumber;
    }

    @Override
    public void run() {
        AtomicInteger currentNumber = new AtomicInteger(0);
        while (true) {
            lock.lock();
            try {
                if (currentNumber.get() > endNumber) {
                    break;
                }
                boolean isOddNumber = currentNumber.get() % 2 != 0;
                if (isOddNumber) {
                    log.info("=====>>>当前线程为: {} , 获取到的奇数为: {}", NyistThreadUtils.getThreadName(), currentNumber.get());
                    // lock.notifyAll();
                } else {
                    // lock.wait();
                }
                currentNumber.addAndGet(1);
            } catch (Exception e) {
                System.out.println(e.getMessage());
            } finally {
                lock.unlock();
            }
        }
    }

    public static void main(String[] args) {
        SumNum sumNum = new SumNum(100);

        Thread t1 = new Thread(sumNum);
        Thread t2 = new Thread(sumNum);
        // Thread t3 = new Thread(sumNum);

        t1.setName("first 1111");
        t2.setName("second 2222");
        // t3.setName("third 3333");

        t1.start();
        t2.start();
        // t3.start();
    }
}
